<template>
    <div class="app-container">
        <el-card class="filter-container" shadow="never">
            <div>
                <i class="el-icon-search"></i>
                <span>筛选搜索</span>
                <el-button style="float:right" type="primary" @click="search()" size="small">
                    查询搜索
                </el-button>
                <el-button 
                    @click="objPage.keyword='',search()"
                    style="float:right;margin-right: 15px" size="small">
                    重置
                </el-button>
            </div>
            <div style="margin-top: 15px">
                <el-form :inline="true" size="small" label-width="140px">
                    <el-form-item label="输入搜索：">
                        <el-input class="input-width" v-model="objPage.keyword" placeholder="帐号/姓名" clearable></el-input>
                    </el-form-item>
                </el-form>
            </div>
        </el-card>
        <el-card class="operate-container" shadow="never">
            <i class="el-icon-tickets"></i>
            <span>数据列表</span>
            <el-button size="mini" class="btn-add" style="margin-left: 20px" @click="addRoleShow = true">添加</el-button>
        </el-card>
        <div class="table-container">
            <!-- elementplus表格 -->
            <el-table :data="list" border :lazy="true">
                <!-- 每一列 -->
                <el-table-column prop="id" label="编号" width="100" align="center" />
                <el-table-column prop="username" label="账号" align="center" />
                <el-table-column prop="nickName" label="姓名" align="center" />
                <el-table-column prop="email" label="邮箱" align="center" />
                <el-table-column label="添加时间" align="center">
                    <!-- 自定义数据格式 -->
                    <template #default="scope">
                        <!-- 插入的scope 是一个对象 里面的row属性是 当前行的数据 -->
                        <span>
                            {{ new Date(scope.row.createTime).toLocaleDateString().replace(/\//g, '-') }}
                            {{ new Date(scope.row.createTime).toLocaleTimeString().replace(/\//g, '-') }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="最后登录" align="center">
                    <template #default="scope">
                        <!-- 插入的scope 是一个对象 里面的row属性是 当前行的数据 -->
                        <span v-if="scope.row.loginTime == null">
                            无
                        </span>
                        <span v-else>
                            {{ new Date(scope.row.loginTime).toLocaleDateString().replace(/\//g, '-') }}
                            {{ new Date(scope.row.loginTime).toLocaleTimeString().replace(/\//g, '-') }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="是否启用" align="center">
                    <template #default="scope">
                        <!-- 插入的scope 是一个对象 里面的row属性是 当前行的数据 -->
                        <el-switch @change="switchChange(scope.row)" v-model="scope.row.status" :active-value="1" :inactive-value="0" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <!-- 插入的scope 是一个对象 里面的row属性是 当前行的数据 -->
                        <el-button link type="primary" size="small" @click="giveRole(scope.row)">
                            分配角色
                        </el-button>
                        <el-button link type="primary" size="small" @click="editRoleDetail(scope.row)">
                            编辑
                        </el-button>
                        <el-button link type="primary" size="small" @click="deletePrepole(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pagination-container">
            <el-pagination
                v-model:current-page="objPage.pageNum"
                v-model:page-size="objPage.pageSize"
                :page-sizes="[5, 10, 20, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pagination.total"
                @size-change="sizeChange"
                @current-change="currentChange"
            />
        </div>
        <el-dialog 
            v-model="roleShow"
            title="分配角色">
            <el-select
                v-model="RoleId"
                multiple
                placeholder="请选择分配的角色"
                style="width: 240px"
                @change="roleChange"
                >
                <el-option
                    v-for="item in roleList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
            </el-select>
            <template #footer>
                <span>
                    <el-button @click="roleShow = false">
                        取消
                    </el-button>
                    <el-button type="primary" @click="editRole()">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog 
            v-model="addRoleShow"
            title="添加角色">
            <el-form :model="roleDetail" label-width="120px">
                <el-form-item label="账号">
                    <el-input v-model="roleDetail.username" />
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="roleDetail.nickName" />
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="roleDetail.email" />
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="roleDetail.password" type="password"/>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="roleDetail.note" type="textarea" />
                </el-form-item>
                <el-form-item label="是否启用">
                    <el-radio-group v-model="roleDetail.status" class="ml-4">
                        <el-radio :label="1" size="large">启用</el-radio>
                        <el-radio :label="0" size="large">不启用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <span>
                    <el-button @click="addRoleShow = false">
                        取消
                    </el-button>
                    <el-button type="primary" @click="addRole()">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog 
            v-model="editRoleShow"
            title="编辑角色">
            <el-form :model="editDetail" label-width="120px">
                <el-form-item label="账号">
                    <el-input v-model="editDetail.username" />
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="editDetail.nickName" />
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="editDetail.email" />
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="editDetail.password" type="password"/>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="editDetail.note" type="textarea" />
                </el-form-item>
                <el-form-item label="是否启用">
                    <el-radio-group v-model="editDetail.status" class="ml-4">
                        <el-radio :label="1" size="large">启用</el-radio>
                        <el-radio :label="0" size="large">不启用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <span>
                    <el-button @click="editRoleShow = false">
                        取消
                    </el-button>
                    <el-button type="primary" @click="editRoleDetailConfirm()">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
// 引入ref
import { ref } from "vue";
// 引入Ref
import type { Ref } from 'vue';
// 导出
import { 
    adminListData, 
    adminListDataType,
    roleListData,
    roleDetailData
} from '@/utils/adminType';
// 导出接口
import { 
    adminList,
    adminDelete,
    adminUpdateStatus,
    roleListAll,
    adminRole,
    adminRoleUpdate,
    adminRegister,
    adminUpdate
} from '@/api/admin'
// 引入elementplus的消息弹框
import { ElMessageBox,ElMessage } from 'element-plus'
import type { Action } from 'element-plus'
// 创建页面请求数据
const objPage: Ref<adminListData> = ref({
    pageNum: 1,
    pageSize: 10,
    keyword: ''
})
// 创建分页显示的数据
const pagination: Ref<{total:number}> = ref({
    total:0
})
// 创建data数据
const list: Ref<adminListDataType[]> = ref([]);
// 调用数据请求接口
getList();
// 创建请求接口
function getList():void {
    // 发起七个球
    adminList(objPage.value).then((res:any) => {
        // 
        if (res.code == 200) {
            list.value = res.data.list;
            // 删除res.data.list
            delete res.data.list
            // 改变分页数据
            pagination.value = res.data;
        }

    })
}

// 每页显示条数改变事件
function sizeChange(e:number):void{
    // 改变pageSize
    objPage.value.pageSize = e;
    // 重新调用接口
    getList();
}

// 页数改变事件
function currentChange(e:number):void{
    // 改变pageNum
    objPage.value.pageNum = e;
    // 重新调用接口
    getList();
}

// 搜索
function search():void{
    // 重置数据
    objPage.value.pageNum = 1;
    objPage.value.pageSize = 10;
    // 调用接口
    getList()
}

// 删除角色
function deletePrepole(data:adminListDataType):void{
    ElMessageBox.alert('是否要删除该用户?', '提示', {
        confirmButtonText: '确定',
        showCancelButton:true,
        callback: (action: Action) => {
            if(action === 'confirm'){
                console.log('点击了确定');
                // 发送删除用户请求
                adminDelete(data.id).then((res:any) => {
                    if(res.code === 500){
                        ElMessage({
                            type: 'error',
                            message: res.message,
                        })
                    }
                })
            }
        }
    })
}

function switchChange(data:adminListDataType):void{
    ElMessageBox.alert('是否要修改该状态?', '提示', {
        confirmButtonText: '确定',
        showCancelButton:true,
        callback: (action: Action) => {
            if(action === 'confirm'){
                console.log();
                adminUpdateStatus({
                    id: data.id,
                    status: data.status
                }).then((res:any) => {
                    if(res.code === 500){
                        ElMessage({
                            type: 'error',
                            message: res.message,
                        })
                    }
                })
            }else{
                // 取消返回原来的状态
                data.status = data.status === 0 ? 1 : 0 
            }
        }
    })
}

// 获取角色列表
getRoleListAll();
// 创建角色列表信息
const roleList:Ref<roleListData[]> = ref([])
function getRoleListAll():void{
    roleListAll().then((res:any) => {
        if(res.code === 200){
            roleList.value = res.data; 
        }
    })
}
// 是否显示分配角色对话框
const roleShow:Ref<boolean> = ref(false);
// 默认选中的角色id
const RoleId:Ref<Array<number | undefined>> = ref([]);
// 当前角色的ID
let id:number|undefined = -1;
// 分配角色
function giveRole(data:adminListDataType):void {
    id = data.id;
    // 获取当前的用户角色
    adminRole(data.id).then((res:any) => {
        if(res.code === 200){
            // 显示对话框
            roleShow.value = true;
            // 把当前用户的角色分配给默认属性
            RoleId.value = res.data.map((item:any) => item.id);
        }
    })
    // RoleId.value.push(data.id)
}
// 选中角色变化
function roleChange(e:number[]):void{
    // 把默认值修改
    RoleId.value = e;
}
// 修改角色权限
function editRole(){
    ElMessageBox.alert('是否要确认?', '提示', {
        confirmButtonText: '确定',
        showCancelButton:true,
        callback: (action: Action) => {
            if(action === 'confirm'){
                // 创建FormData
                let formdata = new FormData();
                formdata.append('adminId',String(id));
                formdata.append('roleIds',String(RoleId.value))
                // 修改权限
                adminRoleUpdate(formdata).then((res:any) => {
                    if(res.code === 500){
                        ElMessage({
                            type: 'error',
                            message: res.message,
                        })
                    }
                })
            }
        }
    })
}

// 是否显示角色的弹框
const addRoleShow:Ref<boolean> = ref(false);
// 角色信息
const roleDetail:Ref<roleDetailData> = ref({
    email: '',
    nickName: '',
    note: 'adasd',
    password: '',
    status: 1,
    username: ''
})
// 添加角色
function addRole():void{
    ElMessageBox.alert('是否要确认?', '提示', {
        confirmButtonText: '确定',
        showCancelButton:true,
        callback: (action: Action) => {
            if(action === 'confirm'){
                if(roleDetail.value.username === ''){
                    ElMessage({
                        type: 'error',
                        message: '账号不能为空',
                    })
                    return 
                }
                if(roleDetail.value.password === ''){
                    ElMessage({
                        type: 'error',
                        message: '密码不能为空',
                    })
                    return 
                }
                // 添加角色
                adminRegister(roleDetail.value).then((res:any) => {
                    if(res.code === 500){
                        ElMessage({
                            type: 'error',
                            message: res.message,
                        })
                    }
                })
            }
        }}
    )
    
}

// 是否显示编辑角色的弹框
const editRoleShow:Ref<boolean> = ref(false);
// 修改的信息
const editDetail:Ref<adminListDataType> = ref({
    id: 0,
    email: '',
    nickName: '',
    note: 'adasd',
    password: '',
    status: 1,
    username: ''
})
// 编辑角色
function editRoleDetail(data:adminListDataType):void{
    // 做了一层浅拷贝
    editDetail.value = Object.assign({},data);
    // 显示编辑弹框
    editRoleShow.value = true;
    
}
// 确认修改
function editRoleDetailConfirm():void{
    ElMessageBox.alert('是否要确认?', '提示', {
        confirmButtonText: '确定',
        showCancelButton:true,
        callback: (action: Action) => {
            if(action === 'confirm'){
                if(editDetail.value.username === ''){
                    ElMessage({
                        type: 'error',
                        message: '账号不能为空',
                    })
                    return 
                }
                if(editDetail.value.password === ''){
                    ElMessage({
                        type: 'error',
                        message: '密码不能为空',
                    })
                    return 
                }
                // 编辑角色
                adminUpdate(editDetail.value).then((res:any) => {
                    if(res.code === 500){
                        ElMessage({
                            type: 'error',
                            message: res.message,
                        })
                    }
                })
            }
        }}
    )
}
</script>